package org

import (
    "fmt"
	"dhfshop/models"
	"github.com/astaxie/beego/orm"
	"dhfshop/service/redisgo"
	"github.com/astaxie/beego"
)

type Permission struct {
	Id        int64  `orm:"auto;pk;column(id)" json:"id"`
	PartnerId int64  `orm:"column(partner_id)" json:"partner_id" form:"partner_id"`
	RoleId    int64  `orm:"column(role_id)" json:"role_id"`
	Menu      string `orm:"column(menu)" json:"menu" form:"menu"`                //菜单
	Module    string `orm:"column(module)" json:"module" form:"module"`          //模块
	Name      string `orm:"column(name)" json:"name" form:"name"`                // 资源名称
	Identity  string `orm:"column(identity)" json:"identity" form:"identity"`    // 资源的唯一标识
	Action    string `orm:"size(32);column(action)" json:"action" form:"action"` //操作（增加、删除、修改、查询等）
}

func init() {
	orm.RegisterModel(new(Permission))
}

// 登陆的时候，加载到缓存中，兼容内存，文件，redis,ssdb等
func LoadPermisRelation(userId int64) (*AuthenticatedUser, error) {
	
	return nil, nil
}

// 获取角色的权限信息
func GetPermissionsByRoleId(roleId int64)(lists []*Permission,err error){
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Permission))
	qs = qs.Filter("role_id", roleId)
	_, err = qs.All(&lists)
	return
}

//创建角色对应的权限
func SavePermission(permissions []*Permission, partnerId, roleId int64) error {
	//判定同名客户是否存在
	o := models.GetDefaultDB()
	/*
	o.Begin()
	o.QueryTable(new(Permission)).Filter("partner_id", partnerId).Filter("role_id", roleId).Delete()
	_, err := o.InsertMulti(500, permissions)
	if err != nil {
		beego.Debug("InsertMulti error.......")
		o.Rollback()
	} else {
	    beego.Debug("InsertMulti correct.......")
		o.Commit()
	}
	cacheKey := fmt.Sprintf("%d_%d", partnerId, roleId)
    redisconn := redisgo.GetInstance()
	if err = redisconn.Del(cacheKey); err != nil {
	    return err
	}
	*/
	
	o.QueryTable(new(Permission)).Filter("partner_id", partnerId).Filter("role_id", roleId).Delete()
	for _, permission := range permissions {
	    _, err := o.Insert(permission)
	    if err != nil {
			beego.Debug("Insert Error:", err.Error())
		} 
	}
	cacheKey := fmt.Sprintf("%d_%d", partnerId, roleId)
    redisconn := redisgo.GetInstance()
	if err := redisconn.Del(cacheKey); err != nil {
	    beego.Debug("redisconn.Del Error:", err.Error())
		//return err
	}
	return nil
}

